package com.linghang.pc;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpGetTest {
    //创建HttpClient对象
    //创建HttpGet对象，设置url访问地址
    //使用Httpclient发起请求，获取response
    // 解析响应
    public static void main(String[] args) {
        // 1. 打开浏览器>>>创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2. 输入网址,模拟发送请求，设置相关参数(例如可设置请求头，响应时间…)
        // (发起get请求，创建HttpGet对象)
        HttpGet httpGet1 = new HttpGet("http://www.itcast.cn");
        // 3. 回车，使用HttpClient对象发起请求，返回响应|发送, 获取响应数据

        //先将try...catch中的response提升至全局变量，不然拿不到
        CloseableHttpResponse response1 = null;
        try {
            response1 = httpClient.execute(httpGet1);
            // 4. 解析响应，获取数据|获取html页面
            //通过状态码判断请求是否正常
            if (response1.getStatusLine().getStatusCode() == 200) {
                //获取响应体
                HttpEntity httpEntity1 = response1.getEntity();
                //解析响应体
                String content1 = EntityUtils.toString(httpEntity1, "utf8");
                System.out.println(content1.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //合理利用资源，释放关闭response
            //先将try...catch中的response提升至全局变量，不然拿不到
            try {
                response1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
